package com.jt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    private RestTemplate restTemplate;
    @Value("${server.port:8080}")
    private String serverPort;
    /**
     * 基于此对象可以从nacos中动态获取服务列表,
     * 并基于内置负载均衡算法获取服务实例,
     * 这里的LoadBalancerClient是一个接口类型,
     * 实际运行spring框架会为此接口类型的变量
     * 注入一个实现类的对象.
     */
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate loadBalancedRestTemplate;

    @Autowired
    public ConsumerController(RestTemplate restTemplate){
        this.restTemplate=restTemplate;
    }
    /**
     * 负载均衡方式的服务调用
     * 调用远端服务.
     * @return
     */
    //http://ip:port/consumer/doRestEcho1
    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho1(){
        //String url="http://localhost:8081/provider/echo/sad";
        //String.class:url对应的响应类型
        //return restTemplate.getForObject(url,String.class);
        //1)基于服务名(这个名字是nacos注册中心中的一个服务名)获取服务实例
        ServiceInstance serviceInstance =
                loadBalancerClient.choose("sca-provider");
        //2)基于服务实例构建远端服务url
        String url ="http://%s:%s/provider/echo/{msg}";
        String ip = serviceInstance.getHost();
        int port = serviceInstance.getPort();
         url = String.format(url, ip, port);
        //3)进行远端服务调用
        return restTemplate.getForObject(url,String.class,serverPort);
    }
    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho2(){
        String url ="http://sca-provider/provider/echo/{msg}";

        return loadBalancedRestTemplate
                .getForObject(url,String.class,serverPort);
    }

}
